package com.example.demo.init;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class SuperAdminInitializer implements CommandLineRunner {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;

    @Value("${superadmin.username}")
    private String superAdminUsername;

    @Value("${superadmin.password}")
    private String superAdminPassword;

    public SuperAdminInitializer(UserService userService, PasswordEncoder passwordEncoder, UserRepository userRepository) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        if (userRepository.findByUsername("superAdmin").isEmpty()) {
            User user = new User();
            user.setUsername(superAdminUsername);
            user.setPassword(passwordEncoder.encode(superAdminPassword));
            user.setAuth("e56e1e0d96783898");
            user.setName("SuperAdmin");
            user.setRegisterTime(LocalDateTime.now());
            userRepository.save(user);
            System.out.println("超级管理员账号已创建，用户名: superAdmin, 初始密码: cloudP5561");
        } else {
            System.out.println("超级管理员账号已创建");
        }
    }
}
